import $ from '@/assets/js/jquery-vendor.js'
import Vue from 'vue';
import CryptoJS from 'crypto-js'

export const _basePath = window.basePath = window.location.protocol + '//' + window.location.host;

// export const _apiPath = 'http://47.108.171.242:10010'
export let _apiPath = _basePath;
if (window.location.port && window.location.port !== '') {
  _apiPath = _basePath.replace((window.location.port), '10010');
}
export let _uploadPath = window.uploadPath = _apiPath = 'https://39.98.203.5:8444';

if (process.env.NODE_ENV === 'development') {
  _uploadPath = window.uploadPath = _apiPath = _basePath.replace((window.location.port), '10010');
}

export const _$storage = {
  clear() {
    sessionStorage.clear()
  },
  setItem(key, val) {
    sessionStorage.setItem(key, val) || _$cookies.setItem(key, val);
  },
  getItem(key) {
    return sessionStorage.getItem(key) || _$cookies.getItem(key);
  },
  removeItem(key) {
    if (sessionStorage) {
      sessionStorage.removeItem(key);
    }
    _$cookies.removeItem(key);
  }
};
export const _$cookies = {
  clear() {
    // eslint-disable-next-line no-useless-escape
    let keys = document.cookie.match(/[^ =;]+(?=\=)/g);
    if (keys) {
      for (let i = keys.length; i--;) {
        document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
      }
    }
  },
  setItem(key, val) {
    // let Days = 30;
    // let exp = new Date();
    // exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    // $cookies.removeItem(key);
    // document.cookie = key + '=' + escape(val) + ';path=/;expires=' + exp.toGMTString();
  },
  getItem(key) {
    // let reg = new RegExp('(^| )' + key + '=([^;]*)(;|$)');
    // let arr = document.cookie.match(reg)
    // if (arr) {
    //   return unescape(arr[2]);
    // } else {
    //   return null;
    // }
  },
  removeItem(key) {
    // let exp = new Date();
    // exp.setTime(exp.getTime() - 1);
    // let cval = $cookies.getItem(key);
    // if (cval !== null) {
    //   document.cookie = key + '=' + cval + ';path=/;expires=' + exp.toGMTString();
    // }
  }
};

export const _axiosContentType = {
  'xWwwFormUrlencoded': {headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}},
  'json': {headers: {'Content-Type': 'application/json;charset=utf-8'}},
  'html': {headers: {'Content-Type': 'text/html;charset=utf-8'}}
};

Vue.prototype.loaderrorimage = window.loaderrorimage = function () {
  let img = event.srcElement;
  img.src = require('@/assets/images/error/404_small.png');
  img.onerror = null; // 解绑onerror事件
};

// 工具类
export const _apiUtil = {
  isHidden(_id) {
    let is = $(_id).is(':hidden')
    // console.info(_id + '=' + is)
    return !!(is || is === 'none');
  },
  notEmpty(p) {
    return !(p === undefined || p === null || p === '' || p === 'null' || p === 'undefined');
  },
  dateTimeFormat(value) {
    if (value) {
      let date = new Date(value); // value为时间戳
      let Y = date.getFullYear() + '-'; // 年
      let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'; // 月
      let D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(); // 日 + ' '; // 日
      let h = date.getHours() + ':'; // 时
      let m = date.getMinutes() + ':'; // 分
      let s = date.getSeconds(); // 秒
      return Y + M + D + ' ' + h + m + s; //  2016-12-7 16:0:12
    }
    return '';
  },
  formatDate(date, fmt) {
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    let o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'H+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds()
    };
    for (let k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        let str = o[k] + '';
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : _apiUtil.padLeftZero(str));
      }
    }
    return fmt;
  },
  padLeftZero(str) {
    return ('00' + str).substr(str.length);
  },
  guid() {
    function S4() {
      return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }

    return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4());
  },
  getQueryString(name) {
    let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    let r = window.location.search.substr(1).match(reg);
    if (r !== null) return unescape(r[2]);
    return null;
  },
  existSessionKey(sessionKey) {
    return !!(_apiUtil.notEmpty(_$storage.getItem(sessionKey)) && _$storage.getItem(sessionKey) !== 0 && _$storage.getItem(sessionKey) !== '0');
  },
  replace(src, oldchar, newchar) {
    let result = src;
    if (this.notEmpty(result)) {
      let patt1 = new RegExp(oldchar, 'g');
      result = src.replace(patt1, newchar);
      if (patt1.test(result)) {
        return this.replace(result, oldchar, newchar);
      } else {
        return result;
      }
    }
    return result;
  },
  removeArrItem(_arr, _obj) {
    if (!_arr || _arr.length === 0) return;
    let length = _arr.length;
    for (let i = 0; i < length; i++) {
      if (_arr[i] === _obj) {
        if (i === 0) {
          _arr.shift(); // 删除并返回数组的第一个元素
          return;
        } else if (i === length - 1) {
          _arr.pop();  // 删除并返回数组的最后一个元素
          return;
        } else {
          _arr.splice(i, 1); // 删除下标为i的元素
          return;
        }
      }
    }
  },
  escapeXml(content) {
    return content.replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&apos;');
  },
  startWith(srcStr, prefix) {
    let depStr = srcStr;
    if (srcStr instanceof Object) {
      depStr = JSON.stringify(srcStr);
    }
    if (!this.notEmpty(depStr) || !this.notEmpty(prefix) || depStr.length === 0 || prefix.length > depStr.length) {
      return false;
    }
    return depStr.substr(0, prefix.length) === prefix;
  },
  endWith(str, prefix) {
    if (prefix === null || prefix === '' || str.length === 0 || prefix.length > str.length) {
      return false;
    }
    return str.substring(str.length - prefix.length) === prefix;
  },
  getLanguage() {
    let lang = 'zh-CN';
    let type = navigator.appName;
    if (type === 'Netscape') {
      lang = navigator.language;// 获取浏览器配置语言，支持非IE浏览器
    } else if (navigator.userLanguage) {
      lang = navigator.userLanguage;// 获取浏览器配置语言，支持IE5+ === navigator.systemLanguage
    }
    return lang
  }
};

Vue.prototype.crypto = {
  md5(_text) {
    return CryptoJS.MD5(_text).toString();
  },
  encrypt(_key, _text) {
    let key = CryptoJS.enc.Utf8.parse(_key);
    let text = CryptoJS.enc.Utf8.parse(_text);
    let encrypted = CryptoJS.DES.encrypt(text, key, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7});
    return encrypted.toString();
  },
  decrypt(_key, _text) {
    let key = CryptoJS.enc.Utf8.parse(_key);
    let decrypt = CryptoJS.DES.decrypt(_text, key, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7});
    return CryptoJS.enc.Utf8.stringify(decrypt).toString();
  }
}

Vue.prototype.$language = window.$language = _apiUtil.getLanguage();
Vue.prototype.util = Vue.prototype.apiUtil = window.apiUtil = _apiUtil;
Vue.prototype.$storage = window.$storage = _$storage;
